using UnityEngine;
using QFramework;
using QAssetBundle;

namespace ProjectSurviver
{
	public partial class Exp : GamePlayObject
	{
        public override Collider2D Collider2D => SelfCollider2D;
		public bool FlyingToPlayer { get; set; }
		private int FlyingToPlayerFrameCount = 0;

        void OnTriggerEnter2D(Collider2D other)
        {
			if(other.GetComponent<CollectableArea>())
			{
				FlyingToPlayer = true;
			}
        }

		public void Execute()
		{
			AudioKit.PlaySound(Sfx.EXP);
			Global.Exp.Value++;
			this.DestroyGameObjGracefully();
		}

        void Update()
        {
            if(FlyingToPlayer)
			{
				if(FlyingToPlayerFrameCount == 0)
				{
					GetComponent<SpriteRenderer>().sortingOrder = 5; // 将Exp的排序层设置为5
				}
				FlyingToPlayerFrameCount++;

				if(Player.Default)
				{
					var direction = Player.Default.DirectionFrom(this);
					var distance = direction.magnitude; // 获取距离

					if(FlyingToPlayerFrameCount <= 15)
					{
						transform.Translate(direction.normalized * -2 * Time.deltaTime); // 移动到Player
					}
					else
					{
						transform.Translate(direction.normalized * 7.5f * Time.deltaTime);
					}

					if(distance < 0.1f)
					{
						Execute();
					}
				}
			}
        }
    }
}
